package com.example.sneakerappserver.controller;

import com.example.sneakerappserver.pojo.ResponseMessage;
import com.example.sneakerappserver.pojo.User;
import com.example.sneakerappserver.service.ICartService;
import com.example.sneakerappserver.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController // 接口方法返回对象 转换成json文本
@RequestMapping("/login")    // localhost:8088/user/**
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ICartService cartService;

    @PostMapping    // /login
    public ResponseMessage<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        User user = userService.queryByUserName(username);
        Map<String, Object> data = new HashMap<>();
        if (user == null) {
            return ResponseMessage.error(404, "用户不存在",data);    // data 为空
        }

        if (!user.getPassword().equals(password)) {
            return ResponseMessage.error(401, "密码错误",data);
        }

        // 获取用户的购物车
        Long cartId = cartService.queryCartByUserId(user.getUserId());
        if (cartId == null) {   // 如果不存在cartId,则进行创建
            cartId = cartService.createCartForUser(user.getUserId()).getCartId();   // 插入购物车后的id
        }


        data.put("userId", user.getUserId());
        data.put("cartId", cartId);
        data.put("role",user.getRole());    //权限

        return ResponseMessage.success(data);
    }




}
